package com.bdqn.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.common.constant.ProductConstant;
import com.bdqn.common.to.SkuHasStockVo;
import com.bdqn.common.to.SkuReductionTo;
import com.bdqn.common.to.SpuBoundsTo;
import com.bdqn.common.to.es.SkuEsModel;
import com.bdqn.common.utils.PageUtils;
import com.bdqn.common.utils.Query;
import com.bdqn.common.utils.R;
import com.bdqn.gulimall.product.dao.SpuInfoDao;
import com.bdqn.gulimall.product.entity.*;
import com.bdqn.gulimall.product.feign.CouponFeignService;
import com.bdqn.gulimall.product.feign.SearchFeignService;
import com.bdqn.gulimall.product.feign.WareFeignService;
import com.bdqn.gulimall.product.service.*;
import com.bdqn.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;//spu信息介绍

    @Resource
    SpuImagesService imagesService;//spu图片

    @Resource
    AttrService attrService;//商品属性

    @Resource
    ProductAttrValueService attrValueService;//spu属性值

    @Resource
    SkuInfoService skuInfoService;//sku信息

    @Resource
    SkuImagesService skuImagesService;//sku图片

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;//sku销售属性&值

    @Resource
    BrandService brandService;

    @Resource
    CategoryService categoryService;

    @Resource
    CouponFeignService couponFeignService;//远程调用优惠券服务

    @Resource
    WareFeignService wareFeignService;//远程调用仓库服务

    @Resource
    SearchFeignService searchFeignService;//远程调用检索服务


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 高级篇写因各种原因导致的新增失败
     * 保存所有数据(商品新增)
     * @param vo
     */
    //Seata AT 分布式事务
    // @GlobalTransactional  高并发场景
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());//商品id
        descEntity.setDecript(String.join(",",decript));//商品介绍
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();//获取vo中的所有图片
        imagesService.saveImages(infoEntity.getId(),images);//传商品id

        //4、保存spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();//所有基本属性
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());//销售属性名
            valueEntity.setAttrValue(attr.getAttrValues());//销售属性值
            valueEntity.setQuickShow(attr.getShowDesc());//是否快速展示
            valueEntity.setSpuId(infoEntity.getId());//商品id

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息 sms_spu_bounds(跨库：gulimall_sms 商品的积分)
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();//to类似于vo，现放在工具类gulimall-common中
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存当前spu对应的所有sku信息

        List<Skus> skus = vo.getSkus();//sku的所有值
        if (skus != null && skus.size()>0){
            skus.forEach(item->{
                String defaultImg = "";

                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){//默认图片
                        defaultImg = image.getImgUrl();//图片的默认url路径
                    }
                }
                // private List<Attr> attr;
                // private String skuName;
                // private BigDecimal price;
                // private String skuTitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();////sku信息
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());//BrandId:品牌id
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());//三级分类id
                skuInfoEntity.setSaleCount(0L);//销量
                skuInfoEntity.setSpuId(infoEntity.getId());//商品id
                skuInfoEntity.setSkuDefaultImg(defaultImg);//sku的默认图片,此字段返回 1(1为true) 则为默认图片
                //6.1、sku的基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();//sku图片
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());//图片的url地址
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());//是否为默认图片 1为true
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true则保存，false就剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());//图片url地址不为空则保存
                }).collect(Collectors.toList());
                //6.2、sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径的无需保存


                List<Attr> attr = item.getAttr();//商品属性
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    //商品属性表
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //6.3、sku的销售属性信息 pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);//sku销售属性&值

                //6.4、sku的优惠、满减等信息 gulimall_sms（另一个数据库）->sms_sku_ladder(几件打几折）\
                // sms_sku_full_reduction
                // (满减表，满什么价减多少钱）\sms_member_price(会员价格表，哪个会员等级对应的会员价格是什么）\
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                if (skuReductionTo.getFullCount() > 0
                        //compareTo:和一个值进行比较,-1：比这个值小 0：和这个值一样 1：比这个值大
                        || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                            R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                            if(r1.getCode() != 0){
                                log.error("远程保存sku优惠信息失败");
                            }
                }

            });
        }





    }

    /**
     * //1、保存spu基本信息 pms_spu_info
     * @param infoEntity
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public void up(Long spuId) {

        //1.查出当前spuid对应的所有sku信息，品牌的名字。
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4.查询所有可以被检索的属性值
        //根据spuId查询pms_product_attr_value里面的数据
        List<ProductAttrValueEntity> productAttrValueEntities = attrValueService.baseAttrListforspu(spuId);

        //遍历出所有的属性id
        List<Long> attrIds = productAttrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        //创建一个set集合
        Set<Long> idSet = new HashSet<Long>(searchAttrIds);


        //过滤返回出最终要添加至里面的所有id
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(item -> {
            //如果idSet里面有这个id，那么就返回出去
            return idSet.contains(item.getAttrId());
        }).map(attr -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();

            BeanUtils.copyProperties(attr, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //TODO 1.发送远程调用，查询是否拥有库存
        Map<Long, Boolean> skuMap=null;
        try{
            R skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> listTypeReference = new TypeReference<List<SkuHasStockVo>>(){

            };
            skuMap = skusHasStock.getData(listTypeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }


        //2.封装每个sku的信息
        Map<Long, Boolean> finalSkuMap = skuMap;
        List<SkuEsModel> skuEsModelList = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            if(finalSkuMap == null){ //Map如果为Null 说明有库存
                esModel.setHasScore(true);
            }else{
                esModel.setHasScore(finalSkuMap.get(sku.getSkuId()));
            }

            //设置检索属性
            esModel.setAttrs(attrsList);





            //TODO 2.热度评分，刚上架的物品，默认给0的热度

            esModel.setHotScore(0L);

            //TODO 3、查询品牌信息（brandName） 与分类信息（catalogName）
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());



            /**
             * skuPrice *
             * skuImg *
             * hasScore
             * hotScore
             * brandName 单独处理
             * brandImg 单独处理
             * catalogName 单独处理
             * List<Attrs> attrs 单独处理
             */
            return esModel;
        }).collect(Collectors.toList());

        //TODO 5.将数据发送给es进行保存；gulimall-search
        R r = searchFeignService.productStatuUp(skuEsModelList);
        if(r.getCode() == 0){
            //调用成功
            //将状态码进行变更
            //TODO 6.修改当前spu的状态码
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //调用失败
            //坑
            //TODO 7、可能会出现 重复调用 接口幂等性；在以后可以使用重试机制进行处理
        }

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


}
